<?php
/**
 * 微信/小程序接口
 * @author maniac
 */
namespace app\api\controller\v1;

use app\facade\Wechat AS WechatFacade;
use think\Db;
use think\Exception;
use think\facade\Env;
use \weixin\jssdk;
use weixin\WXBizDataCrypt;

class Wechat extends Base
{
    /**
     * 用户登录
     */
    public function login()
    {
        $post = input('post.');
        try {
            $result = WechatFacade::add($post);
            if ($result) {
                return j(0, '登录成功', $result);
            }
            return j(1, '登录失败');
        } catch (\Exception $e) {
            return j(1, '', $e->getMessage());
        }
    }
    
    /**
     * 获取用户信息
     */
    public function info()
    {
        $userToken = input('post.userToken/s', '');
        if (!$userToken) {
            return j(1, '请先登录');
        }
        try {
            $data = WechatFacade::info($userToken);
            if ($data) {
                return j(0, '获取用户信息成功', $data);
            }
            return j(1, '获取用户信息失败');
        } catch (\Exception $e) {
            return j(1, '', $e->getMessage());
        }
    }
    
    /**
     * 微信支付回调
     */
    public function notify()
    {

        $xml       = file_get_contents('php://input');
        $xmlString = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
        $data      = json_decode(json_encode($xmlString),true);

        WechatFacade::notify($data);
    }

    /**
     * 获取微信配置
     */
    public function config(){

        $url =input('url','');


//        try {

//            $Wx = new JSSDK(config('site.app_id'),config('site.app_secret'));

            $data = WechatFacade::getSignPackage(config('site.app_id'),config('site.app_secret'),$url);

            return j(0, '获取信息成功', $data);

//        } catch (\Exception $e) {
//
//            return j(1, $e->getMessage());
//
//        }

    }

    /**
     * 微信支付回调
     */
    public function ceshi()
    {
        $data['out_trade_no'] = 'RCH2019093015342884181';
        WechatFacade::rechargePayOk($data,0);
    }

	/*获取手机号*/

	public function weixinGetData(){
		$rootPath = str_replace('\\', '/', Env::get('root_path'));
		require $rootPath.'extend/weixin/wxBizDataCrypt.php';
		$data=array();
        $user_id = $this->checkUserToken();
		$code   =   input('code');

		$encryptedData   =   input('encryptedData');

		$iv   =   input('iv');

		if(empty($code)){

			return j(1, 'CODE为空', []);

		}
        Db::startTrans();
        try {
            $app_id=config('site.app_id');
            $secret=config('site.app_secret');

            $url="https://api.weixin.qq.com/sns/jscode2session?appId=".$app_id."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";

            $arrContextOptions = [
                'ssl' => [
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                ]
            ];
            $apiData=file_get_contents($url, false, stream_context_create($arrContextOptions));

            $apiData=json_decode($apiData,true);

            if(!isset($apiData['errcode'])){

                $sessionKey = $apiData["session_key"];

                $userifo = new WXBizDataCrypt($app_id, $sessionKey);

                $errCode = $userifo->decryptData($encryptedData, $iv, $data );

                file_put_contents('$errCode.txt',$errCode);


                if ($errCode == 0) {

                    $data = json_decode($data,true);
                    $userToken = (new Index())->bindingMobile($data['phoneNumber'],$user_id);
                    Db::commit();
                    return j(0,"绑定成功",$userToken);

                } else {
                    \exception('解密失败');

                }
            }else{
                \exception('获取SESSION失败');
            }

        } catch (Exception $exception) {
            Db::rollback();
            return j(1,$exception->getMessage());
        }
	}

}
